<?php

class HTech_Controller_Action_Helper_Browse extends Zend_Controller_Action_Helper_Abstract
{        
    private $_model;
    
    public function setModel(HTech_Db_Table $model)
    {
        $this->_model = $model;
        return $this;
    }
    
    public function process()
    {
        $filters = array('*' => 'StringTrim');
        $input = new Zend_Filter_Input($filters, null, $this->getRequest()->getParams() + $this->getRequest()->getPost());        
        
        if ($input->isValid()) {
            
            $view = $this->getActionController()->view;
            
            $view->meta = $this->_model->getGridMetadata();
            
            $view->identifier = current($this->_model->info('primary'));
            
            $view->filter = $input->sfilter ? urldecode($input->sfilter) : '';
            if($input->filter) $view->filter = $input->filter;
            $view->filter = preg_replace('/\s{2,}/',' ', $view->filter);
            
            $view->request = array();  
            
            $view->request['module'] = $input->module;
            $view->request['controller'] = $input->controller;
            $view->request['action'] = $input->action;              
            $view->request['page'] = $input->page; 
            /*
             * account for url params if allowed by the model
             */
            $view->request['par'] = array();
            foreach($view->meta['params'] as $par)
                if(isset($input->$par)) $view->request['par'][$par] = $input->$par;
            /*
             * account for grid's title mods if allowed by the model
             */
            $view->request['mod'] = array();
            foreach($view->meta['titleMods'] as $mod)
                if(isset($input->$mod)) $view->request['mod'][$mod] = $input->$mod;
                                
            $view->request['baseUrl'] = $view->baseUrl();
            
            /*
             * Preparing sql select
             */
            $select = $this->_model->select();         
            
            /*
             * Narrow select results depending on model params
             */
            foreach($view->request['par'] as $par => $pval)
                $select->where(sprintf("%s = '%s'", $par, $pval));
            
            /*
             * Narrow select results depending on manual criteria
             * typed in the grid's search field
             */
            foreach(explode(' ', $view->filter) as $fpar) { 
                $filter = array();
                $headers = $view->meta['headers'];
                foreach ($headers as $header)
                    $filter[] = sprintf("%s like '%%%s%%'", $header[0], $fpar);
                $select->where(implode(' or ', $filter));            
            } 
            /*
             * fetch results
             */
            if(!isset($input->format)) {
                $this->getActionController()->getHelper('layout')->setLayout('grid');
                $view->paginator = Zend_Paginator::factory($select);
                $session = new Zend_Session_Namespace('HTech');
                if($input->icpp) $session->icpp = $input->icpp;
                if($session->icpp) $view->paginator->setItemCountPerPage($session->icpp);
                $view->paginator->setCurrentPageNumber($view->request['page']);
                $view->data = self::_formatData($view->paginator->getCurrentItems()->toArray(),$view->meta); 
            } else {
                $view->data = $this->_model->fetchAll($select)->toArray();
            }
        }
        return;
    }
    
    private function _formatData($data,$meta)
    {
        $translate = Zend_Registry::get('Zend_Translate');
        foreach($data as $inx => $row) {
            foreach($meta['headers'] as $col) {
                if($col[1] == 0) {
                    $data[$inx][$col[0]] = '';
                } else {
                    $data[$inx][$col[0]] = $translate->_($data[$inx][$col[0]]);
                    switch ($col[4]) {
                        case 'Standard':
                            $data[$inx][$col[0]] = number_format($row[$col[0]],2,'.',','); 
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        return $data;
    }
}